<template>
  <el-dialog v-if="openForm" v-model="openBoole" :close-on-click-modal="false" custom-class="mydialog" width="50%"
    title="选择终端" @close="close">
    <el-form ref="openRef" :model="openForm" :rules="rules" size="small">
      <el-row gutter="40">
        <el-col :span="9">
          <el-form-item prop="area">
            <el-cascader ref="cascader" v-model="openForm.area" :popper-append-to-body="false" style="width: 100%;"
              :options="region" placeholder="所在地区"
              :props="{ multiple: true, expandTrigger: 'hover', label: 'regionName', value:'regionCode' }" collapse-tags
              @change="handlArea" />
          </el-form-item>
        </el-col>

        <el-col :span="5">
          <el-form-item style="width: 100%">
            <el-select v-model="openForm.terminalType" clearable style="width: 100%" placeholder="请选择终端类型">
              <el-option v-for="item in terminalData.filter(a=>a.value !== 'all')" :key="item.id" :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="5">
          <el-form-item style="width: 100%">
            <el-input v-model="openForm.selectStr" clearable placeholder="输入编号、名称、地区、详细地址" />
          </el-form-item>
        </el-col>

        <el-col :span="5">
          <el-form-item style="width: 100%">
            <!--            <el-button class="border-btn" @click="handlReset">重置</el-button>-->
            <el-button type="primary" class="main-btn" @click="handlSearch">搜索</el-button>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item style="width: 100%" props="tableData">
            <el-table ref="multipleTable" v-table="tableLoadMore" :data="openForm.tableData"
              header-cell-class-name="table-header" size="medium" height="300" border :row-key="handlRowKey"
              @selection-change="handleSelectionChange">
              <el-table-column type="selection" :reserve-selection="true" width="55" />

              <el-table-column prop="terminalName" :min-width="160" label="终端名称" header-align="center"
                :show-overflow-tooltip="true" />

              <el-table-column :min-width="120" label="终端类型" align="center" :show-overflow-tooltip="true">
                <template #default="{row}">
                  {{ getLabel('app_mode', row.terminalType) }}
                </template>
              </el-table-column>

              <el-table-column label="所在地区" :min-width="180" header-align="center" :show-overflow-tooltip="true">
                <template #default="{row}">
                  {{ row.provinceName }}/{{ row.cityName }}/{{ row.areaName }}
                </template>
              </el-table-column>

              <el-table-column prop="address" label="详细地址" :min-width="180" header-align="center"
                :show-overflow-tooltip="true" />

            </el-table>
          </el-form-item>
          <!-- <Pagination v-model:page="openForm.page" v-model:limit="openForm.pageSize"
            style="display: flex; justify-content: flex-end;padding: 0" :total="total" @pagination="handlList" /> -->
        </el-col>

      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer" style="display:flex;justify-content:center;align-items:center;">
        <el-button class="border-btn" size="small" style="margin-right: 20px;" @click="close">取消</el-button>

        <el-button class="main-btn" size="small" type="primary" @click="handlSubmit">添加</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { getCurrentInstance, inject, onMounted, reactive, toRefs } from "vue";
import { crmStore } from "@CRM/store";
import { getScreenAreaData } from "@/utils/areaFuc.js";

export default {
  name: "Terminal",
  setup(props, context) {
    const validateTable = (rule, value, callback) => {
      if (data.multipleSelection.length === 0) {
        callback(new Error("请至少选择一个终端"));
      } else {
        callback();
      }
    };
    const currentInstance = getCurrentInstance();
    const api = inject("api");
    const data = reactive({
      openForm: {
        selectStr: "",
        terminalType: "",
        provinceCode: [],
        cityCode: [],
        areaCode: [],
        area: [],
        pageSize: 20,
        page: 1,
        tableData: [],
      },
      region: [],
      openRef: null,
      terminalData: crmStore.getters["dictionary/getDictionary"]["app_mode"],
      total: 0,
      openBoole: false,
      multipleSelection: [],
      rules: {
        tableData: [
          { validator: validateTable, tyep: "array", trigger: "change" },
        ],
      },
      multipleTable: null,
    });

    const handlArea = (val) => {
      data.openForm.provinceCode = getAreaCode(val).provinceCode;
      data.openForm.cityCode = getAreaCode(val).cityCode;
      data.openForm.areaCode = getAreaCode(val).areaCode;
      handlList();
    };

    const close = () => {
      data.openBoole = false;
      data.openRef.clearValidate();
      data.openRef.resetFields();
    };

    const open = (val) => {
      data.multipleSelection = val.terminalList;
      console.log(val, "-=-==-=--==-=-");
      data.openForm.area = val.area;
      data.region = getScreenAreaData(val.region);
      console.log(data.region, "-----------------");
      data.openForm.provinceCode = getAreaCode(val.area).provinceCode;
      data.openForm.cityCode = getAreaCode(val.area).cityCode;
      data.openForm.areaCode = getAreaCode(val.area).areaCode;
      data.multipleTable?.clearSelection();
      handlList();
      data.openBoole = true;
    };

    const toggleSelection = (rows) => {
      // data.multipleTable.clearSelection();
      if (rows) {
        rows.forEach((row) => {
          data.multipleTable.toggleRowSelection(row, undefined);
        });
      }
    };

    const getAreaCode = (list) => {
      const a = {
        provinceCode: [],
        cityCode: [],
        areaCode: [],
      };
      for (let i = 0; i < list.length; i++) {
        const area = list[i];
        if (area[0]) {
          a.provinceCode.push(area[0]);
        }
        if (area[1]) {
          a.cityCode.push(area[1]);
        }
        if (area[2]) {
          a.areaCode.push(area[2]);
        }
      }

      return a;
    };

    // 获取列表
    const handlList = () => {
      api.terminal.TERMINAL_LIST(data.openForm).then((res) => {
        if (res.code === 0) {
          if (data.openForm.page == 1) {
            data.openForm.tableData = res.data.list || [];
          } else {
            data.openForm.tableData = data.openForm.tableData.concat(
              res.data.list
            );
          }
          data.total = res.data.total;
        }
      });
    };

    const tableLoadMore = () => {
      if (data.openForm.tableData.length < data.total) {
        data.openForm.page++;
        handlList();
      } else {
        currentInstance.proxy.customMessage({
          type: "warning",
          message: "数据已到底了",
        });
      }
    };

    // 重置表格
    const handlReset = () => {
      data.openForm = {
        selectStr: "",
        terminalType: "",
        provinceCode: [],
        cityCode: [],
        areaCode: [],
        area: [],
        pageSize: 20,
        page: 1,
      };
      handlList();
    };

    // 搜索表格
    const handlSearch = () => {
      data.openForm.page = 1;
      handlList();
    };

    const handlRowKey = (row) => {
      return row.id || row.terminalId;
    };

    const handleSelectionChange = (val) => {
      let arr = [];
      val.forEach((item) => {
        arr.push({
          terminalName: item.terminalName,
          terminalId: item.id,
          ifSelect: true,
        });
      });
      arr = handlUnique(arr, "terminalId");
      data.multipleSelection = arr;
    };

    const handlUnique = (arr, id) => {
      const res = new Map();
      return arr.filter((arr) => !res.has(arr[id]) && res.set(arr[id], 1));
    };

    const handlSubmit = () => {
      data.openRef.validate((valid) => {
        if (valid) {
          context.emit("succsess", data.multipleSelection);
          close();
        }
      });
    };

    onMounted(() => {
      handlList();
    });

    return {
      ...toRefs(data),
      close,
      open,
      handlList,
      handlReset,
      handlSearch,
      handlRowKey,
      handleSelectionChange,
      handlSubmit,
      getAreaCode,
      handlArea,
      toggleSelection,
      handlUnique,
      tableLoadMore,
    };
  },
};
</script>

<style scoped>
/* @import url(); 引入css类 */
</style>
